package Map;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class HashMao {
    public static void main(String[] args) throws Exception {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// 创建一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);
// 向HashMap中添加数据
        for (int i = 0; i < 100; i++) {
            map.put("key" + i, i);
        }


// 提交任务到线程池
        List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new ReadTask(map), new WriteTask(map)));

// 获取任务结果
        int sum1 = futures.get(0).get();
        int sum2 = futures.get(1).get();

// 关闭线程池
        executor.shutdown();

// 输出结果
        System.out.println("Sum of values in the map: " + sum1);
        System.out.println("Sum of values in the map after modification: " + sum2);
    }
}

class ReadTask implements Callable<Integer> {
    private final ConcurrentHashMap<String, Integer> map;

    public ReadTask(ConcurrentHashMap<String, Integer> map) {
        this.map = map;
    }

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += map.get("key" + i);
        }
        return sum;
    }
}

class WriteTask implements Callable<Integer> {
    private final ConcurrentHashMap<String, Integer> map;

    public WriteTask(ConcurrentHashMap<String, Integer> map) {
        this.map = map;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 100; i++) {
            map.put("key" + i, i * 2);
        }
        return 0;
    }
}
